// pages/termAdd/index.js
import { request } from '../../request/index'
Page({
  uploadFile: function () {
    var that = this
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        that.setData({
          img: res.tempFilePaths[0]
        })
      }
    })
  },
  nameInput: function (e) {
    this.setData({
      name: e.detail.value
    })
  },
  contentInput: function (e) {
    this.setData({
      content: e.detail.value
    })
  },
  scaleInput: function (e) {
    this.setData({
      scale: e.detail.value
    })
  },
  dateInput: function (e) {
    this.setData({
      time: e.detail.value
    })
  },
  adviceInput: function (e) {
    this.setData({
      advice: e.detail.value
    })
  },
  price: function (e) {
    this.setData({
      price: e.detail.value
    })
  },
  min: function (e) {
    this.setData({
      min: e.detail.value
    })
  },
  submit: function () {
    var app = getApp()
    var data = {
      userId: app.globalData.userId,
      name: this.data.name,
      content: this.data.content,
      scale: this.data.scale,
      time: this.data.time,
      advice: this.data.advice,
      price: this.data.price,
      min: this.data.min,
      imgUrl: ''
    }
    // 提交表单
    request({ url: app.globalData.root + 'api/addTerm', data: data, dataType: 'json', method: 'POST' }).then((res) => {
      // 表单提交成功 后端返回订单id
      // 用订单id去上传图片
      wx.uploadFile({
        url: app.globalData.root+'api/TermUpload', //仅为示例，非真实的接口地址
        filePath: this.data.img,
        name: '图片',
        formData: {
          'id': ''+res.data.id
        },
        complete(){
          wx.showToast({
            title: '添加成功',
            icon: 'success',
            duration: 3000,
            complete:function(){
              var timeId = setTimeout(() => {
                clearTimeout(timeId)
                wx.navigateBack({
                  delta: 1
                })
              }, 2000);
            }
          })
        }
      })
    })
  },
  /**
   * 页面的初始数据
   */
  data: {
    img: '',
    name: '',
    content: '',
    scale: '',
    time: '',
    advice: '',
    price: 0,
    min: 8
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})